const puppeteer = require('puppeteer');

(async () => {
	let browser = await puppeteer.launch();
	let page = await browser.newPage();
	let url = `https://movie.douban.com/subject/26842702`;

	await page.goto(url, {
		wainUntil: ['networkidle0']
	});

	await sleep(1000);

	let result = await page.evaluate(() => {
		let $ = window.$;
		let items = $('.related-pic-video');

		if (items && items.length > 0) {
			let link = items.attr('href');
			let cover = items.attr('style').replace('background-image:url(', '').replace(')', '');

			return {
				link,
				cover
			};
		}
	});

	let videoResult = null;
	if (result.link) {
		await page.goto(result.link, {
			wainUntil: ['networkidle0']
		});

		videoResult = await page.evaluate(() => {
			let $ = window.$;
			let items = $('source');

			if (items && items.length > 0) {
				let video = items.attr('src');

				return {
					video
				};
			}
		});
	}


	browser.close();
	process.send({
		movieId: '26842702',
		cover: result.cover,
		video: videoResult.video
	});
	process.exit(0);
})();

const sleep = time => new Promise((resolve, reject) => {
	setTimeout(resolve, time);
});